class Solution(object):
    def maximumInvitations(self, favorite):
        n = len(favorite)
        p = [0] * n
        s = [0] * n
        for  num in favorite:
            p[num] += 1
        now = set()
        for index, num in enumerate(p):
            if num == 0:
                now.add(index)
        dist = 0
        while now:
            next_st = set()
            dist += 1
            for node in now:
                next_node = favorite[node]
                s[next_node] = dist
                p[next_node] -= 1
                if p[next_node] == 0:
                    next_st.add(next_node)
            now = next_st
        ans = 0
        now_ans = 0
        for node in range(n):
            if p[node] == 1:
                p[node] = 0
                st = {node}
                while favorite[node] not in st:
                    st.add(favorite[node])
                    node = favorite[node]
                    p[node] = 0
                st = list(st)
                if len(st) == 2:
                    now_ans += 2 + s[st[0]] + s[st[1]]
                else:
                    ans = max(ans, len(st))
        ans = max(now_ans, ans)
        return ans

            



data = Solution()
favorite = [2, 2, 1, 2]
favorite = [1,0,3,2,5,6,7,4,9,8,11,10,11,12,10]
print(data.maximumInvitations(favorite))